<?php
class m_ujian extends CI_Model
{
	public $table = 'ujian';
	public $primary_key = 'uj_id';
	
	function get_data_by_id($id){
		$this->db->select("*");
		$this->db -> from($this->table);
		$this -> db -> where($this->primary_key, $id);

		$query = $this -> db -> get();
		
		return $query->row_array();		
	}
	
	function get_data_with_mp($where=null){
		$this->db->select("*");
		$this->db->from($this->table);
		$this->db->join('mata_pelajaran', 'mata_pelajaran.mp_id = ujian.mp_id', 'inner');
		if($where)$this->db->where($where);
	
		$query = $this->db->get();
	
		return $query->result();		
	}
	
	function get_past_ujian($where){
		$this->db->select("*");
		$this->db->from($this->table);
		$this->db->join('mata_pelajaran', 'mata_pelajaran.mp_id = ujian.mp_id', 'inner');
		$this->db->where($where[0]);
		$this->db->or_where($where[1]);
	
		$query = $this->db->get();
	
		return $query->result();		
	}
	
	function count_ujian_by_swid($uj_id, $sw_id){
		$this->db->select("*");
		$this->db->from($this->table);
		$this->db->join('nilai', 'nilai.uj_id = ujian.uj_id', 'inner');
		$this->db->where($this->table.'.'.$this->primary_key, $uj_id);
		$this->db->where('nilai.sw_id', $sw_id);
		
		$query = $this->db->get();
		
		return $query->num_rows();
	}
	
	function get_detail($id){
		$sql = "SELECT * FROM ( 
					SELECT a.* , b.nilai, b.sw_id, e.mp_name, e.mp_passgrade FROM ujian a 
					INNER JOIN nilai b ON a.uj_id = b.uj_id 
					INNER JOIN mata_pelajaran e ON a.mp_id = e.mp_id 
					WHERE a.uj_id = $id
				) a 
				RIGHT JOIN siswa b ON a.sw_id = b.sw_id
				INNER JOIN kelas c ON b.kl_id = c.kl_id
				WHERE b.kl_id IN (SELECT kl_id FROM kelas_ujian WHERE uj_id = $id)";
	
		$query = $this->db->query($sql);
	
		return $query->result();		
	}
	
	function get_ujian_with_soal($id, $opt_where = array()){
		$this->db->select("*");
		$this->db->from($this->table);
		$this->db->join('soal', 'soal.uj_id = ujian.uj_id', 'inner');
		$this->db->join('jawaban', 'soal.so_id = jawaban.so_id', 'inner');
		$this->db->join('mata_pelajaran', 'mata_pelajaran.mp_id = ujian.mp_id', 'inner');
		$this->db->where($this->table.'.'.$this->primary_key, $id);
		foreach ($opt_where as $where){
			$this->db->where($where);
		}
	
		$query = $this->db->get();
	
		return $query->result();
	}
	
	function insert($value){
		$this->db->insert($this->table, $value);
		return mysql_insert_id();
	}
	
	function update($value, $where){
		return $this->db->update($this->table, $value, $where);
	}
	
	function delete($where){
		return $this->db->delete($this->table, $where);
	}
}
?>